<template>
  <el-dialog :visible.sync="visible" :close-on-click-modal="false" :title="$tt('title_pick_scheduling')"
    custom-class="dialog_default">


    <el-form :label-width="$globalCss.formLabelWidth_default" :model="formData" :rules="rules" label-position="right"
      ref="WaveRuleForm" style="max-height: 85vh;overflow-y:auto">
      <el-form-item :label="$tt('text_has_select_order')">
        <ex_super_table :model="optionTableModel" :data="itemList" max-height="250" />
      </el-form-item>
      <el-form-item :label="$tt('label_scheduling_rule')">
        <el-input v-model="searchKey" clearable :placeholder="$tt('tip_please_input_scheduling_name_code')"
          class="form_input_default">
          <el-button slot="append" icon="el-icon-search" @click="search">{{ $tt('label_search') }}</el-button>
        </el-input>
      </el-form-item>

      <el-form-item :label="$tt('label_rule_list')">
        <ex_super_table ref="MainTable" v-bind="tableOption" :data="_waveRuleList"
          @selection-change="e => selection = e" :autoPage="false" height="250" />
      </el-form-item>
      <el-form-item :label="$tt('label_extra_select')">
        <el-checkbox v-model="immediately" :label="$tt('label_immediately_create_picking_task')" border></el-checkbox>
      </el-form-item>


    </el-form>

    <span slot="footer" class="dialog_footer">
      <el-button @click="visible = false">{{ $tt('label_cancel') }}</el-button>
      <el-button type="primary" @click="submit">{{ $tt('label_submit') }}</el-button>
    </span>

  </el-dialog>
</template>

<script>

export default {
  route_manual: true,

  data() {
    return {
      searchKey: "",
      visible: false,
      immediately: false,
      itemList: [],
      optionTableModel: [
        { key: 'outOrderNo', label: 'label_outbound_code' },
        { key: 'omsOrderNo', label: 'label_order_code' },
        {
          type: 'operate', operate: [
            {
              label: 'label_remove', class: 'button_text_danger', click: (row, i) => {
                this.itemList.splice(i, 1)
                if (_.isEmpty(this.itemList)) this.visible = false
              }
            },

          ]
        }
      ],
      selection: [],
      tableOption: {
        model: [

          { type: 'selection', clickToggle: true },
          { key: 'code', label: 'label_scheduling_rule_code', },
          {
            key: 'name', label: 'label_scheduling_rule_name',
            render: (h, { row, column }) => {
              const value = row.code
              if (value == "ORDER_STRUCTURE") {
                return (<div class="flex_center">
                  {row.name}
                  <el-popover
                    placement="right"
                    width="200"
                    trigger="hover"
                    content={this.$t('tip_create_wave_type_order_structure')}>
                    <div slot="reference" style="width:30px"> <i class="el-icon-question"></i></div>
                  </el-popover>
                </div>)
              } else {
                return row.name
              }
            }
          },
        ],
      },
      formData: {
      },
      rules: {
        orderStructure: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }]
      }
    }
  },
  props: {


  },

  computed: {
    _waveRuleList: function () {
      let _list = this.$enumOptions['WavePlanRuleEnum'].map(it => {
        return {
          code: it,
          name: this.$enumShow(it, 'WavePlanRuleEnum')
        }
      })
      // let _list =  [
      //   { code: 'SKU', name: this.$tt('label_sku'), },
      //   { code: 'CHANNEL', name: this.$tt('label_logistics_supplier'),  },
      //   { code: 'CUSTOMER', name: this.$tt('label_customer'), },
      //   { code: 'WAREHOUSE_AREA', name:this.$tt('label_warehouse_area'), },
      // ]
      return _list.filter(it => {
        if (this.searchKey) {
          let reg = new RegExp(_.escapeRegExp(this.searchKey))
          return reg.test(it.name) || reg.test(it.code)
        }
        return it
      })
    },
  },
  methods: {
    search() {

    },
    show({ itemList }) {
      this.visible = true
      this.itemList = _.cloneDeep(itemList)
      this.immediately = false
      if (this.$refs['MainTable']) this.$refs['MainTable'].clearSelection();

      this.formData = {
      }
    },
    hide() {
      this.visible = false
    },

    submit() {
      if (this.$clickFast()) return
      this.$refs['WaveRuleForm'].validate((valid) => {

        if (valid) {
          let select = this.selection;
          if (select.length == 0) {
            return this.$message.error(this.$tt("tip_no_select_scheduling_rule"))
          }
          if (this.immediately) {
            this.submitPickingTask(select)
          } else {
            this.submitWavePlan(select)
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    submitWavePlan(select) {
      this.$ajax({
        url: "/wms-api/outbound/OutboundWavePlanRpc/createWavePlan.json",
        method: 'post', type: 'json', loading: true,
        data: {
          waveRule: _.join(select.map(it => it.code), ','),
          orderIds: this.itemList.map(it => it.id),
        },
        success: (res) => {
          if (res.data && res.data.errorOrderList && res.data.errorOrderList.length) {
            if (_.isEmpty(res.data.successOrderList)) {
              this.$message.error(this.$tt("tip_all_order_create_fail"))

              this.$emit('afterSubmitFail')
            } else {
              this.$message.warning(this.$tt("tip_part_order_create_fail"))

              this.$emit('afterSubmitSuccess')
            }
            this.$msgbox_table({
              note: this.$tt('label_order_failed_to_operate'),
              tableProp: {
                data: res.data.errorOrderList,
                model: [
                  { key: 'orderNo', label: 'label_outbound_code', 'min-width': 120, 'show-overflow-tooltip': true, },
                  { key: 'message', label: 'label_info', 'min-width': 120, 'show-overflow-tooltip': true, }
                ],
              },
            }, { type: 'error', customClass: 'dialog_small' })
          } else {
            this.$message.success(this.$tt("tip_create_success"))
            this.visible = false
            this.$emit('afterSubmitSuccess')
          }

        },
      })
    },
    submitPickingTask(select) {
      this.$ajax({
        url: "/wms-api/outbound/OutboundPickingTaskRpc/createPickingTask.json",
        method: 'post', type: 'json', loading: true,
        data: {
          waveRule: _.join(select.map(it => it.code), ','),
          orderIds: this.itemList.map(it => it.id),
          ...this.formData
        },
        success: (res) => {
          if (res.data && res.data.errorOrderList && res.data.errorOrderList.length) {
            if (_.isEmpty(res.data.successOrderList)) {
              this.$message.error(this.$tt("tip_all_order_create_fail"))

              this.$emit('afterSubmitFail')
            } else {
              this.$message.warning(this.$tt("tip_part_order_create_fail"))

              this.$emit('afterSubmitSuccess')
            }
            this.$msgbox_table({
              note: this.$tt('label_order_failed_to_operate'),
              tableProp: {
                data: res.data.errorOrderList,
                model: [
                  { key: 'orderNo', label: 'label_outbound_code', 'min-width': 120, 'show-overflow-tooltip': true, },
                  { key: 'message', label: 'label_info', 'min-width': 120, 'show-overflow-tooltip': true, }
                ],
              },
            }, { type: 'error', customClass: 'dialog_small' })
          } else {
            this.$message.success(this.$tt("tip_create_success"))
            this.visible = false
            this.$emit('afterSubmitSuccess')
          }

        },
      })
    },
  }
}
</script>
